#include "PclViewer.h"

#include <vtkGenericOpenGLRenderWindow.h>

#include <QDebug>

#include "ui_PclViewer.h"

PCLViewer::PCLViewer(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::PCLViewer)
{
    ui->setupUi(this);
    this->setWindowTitle("PCL viewer");

    // 设置QVTK窗口
    auto renderer = vtkSmartPointer<vtkRenderer>::New();
    auto renderWindow = vtkSmartPointer<vtkGenericOpenGLRenderWindow>::New();
    renderWindow->AddRenderer(renderer);
    m_viewer.reset(new pcl::visualization::PCLVisualizer(renderer, renderWindow, "viewer", false));
    ui->qvtkWidget->setRenderWindow(m_viewer->getRenderWindow());

    // 添加坐标轴
    m_viewer->addOrientationMarkerWidgetAxes(ui->qvtkWidget->interactor());

    connect(this, &PCLViewer::updatePoint, this, &PCLViewer::onUpdatePoint);
}

PCLViewer::~PCLViewer()
{
    delete ui;
}

void PCLViewer::onUpdatePoint(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr data)
{
    m_viewer->resetCamera();
    if (!m_viewer->addPointCloud(data, "cloud")) {
        m_viewer->updatePointCloud(data, "cloud");
    }
    ui->qvtkWidget->renderWindow()->Render();
}

void PCLViewer::on_pbAddCloud_clicked()
{
    pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGBA>);
    cloud->resize(500);
    // 添加500个点
    for (auto &point : *cloud) {
        point.x = 1024 * rand() / (RAND_MAX + 1.0f);
        point.y = 1024 * rand() / (RAND_MAX + 1.0f);
        point.z = 1024 * rand() / (RAND_MAX + 1.0f);

        point.r = 255 * (1024 * rand() / (RAND_MAX + 1.0f));
        point.g = 255 * (1024 * rand() / (RAND_MAX + 1.0f));
        point.b = 255 * (1024 * rand() / (RAND_MAX + 1.0f));
    }
    emit updatePoint(cloud);
}
